<template>
	<!-- 横幅管理页面 -->
	<!-- 头部标题 -->
	<view class="header header-position" v-if="bannerList.length > 0">
		<text>横幅图片</text>
		<text>操作</text>
	</view>
	<!-- 防止因头部定位脱离文档流导致后面的挤上去 -->
	<view style="height: 90rpx;"></view>

	<!-- 展示已经设置的横幅图片 -->
	<view class="header content-list" v-for="(item,index) in bannerList" :key="index">
		<image :src="item.banner_cover" mode="aspectFill"></image>
		<text class="operation" @click="delBanner(item._id,index)">删除</text>
	</view>

	<!-- 没有数据的提示 -->
	<view class="tips" v-if="bannerList.length === 0">你还没有横幅数据</view>

	<!-- 底部 -->
	<view style="300rpx"></view>
	<view class="bottom-button-position">
		<view class="bottom-button-style" @click="show = true">新增横幅</view>
	</view>

	<!-- 弹窗 -->
	<page-container :show="show" position="bottom" @click="onEnter" @clickoverlay="show = false">
		<view class="space-view">
			<!-- 弹窗头部 -->
			<view class="popup-title popup-padding">
				<image @click="show = false" src="/static/images/close.svg" mode="widthFix"></image>
				<text>新增横幅</text>
				<text @click="submit">提交</text>
			</view>
			<!-- 上传横幅部分 -->
			<view class="upload-cover">
				<image @click="uploadImg" v-if="banner_cover == ''" src="/static/images/seckill-img.jpg" mode="aspectFill"></image>
				<image :src="banner_cover" mode="aspectFill"></image>
				<image @click="delImg" v-if="banner_cover != ''" src="/static/images/delete-goods.svg" mode="widthFix"></image>
			</view>
			<!-- 关联商品部分 -->
			<view class="relation relation-back" @click="addRelated">
				<text>关联商品</text>
				<text class="over-text">{{relatedData.title == '' ? '添加' : relatedData.title}}</text>
			</view>
		</view>
	</page-container>

</template>

<script setup>
	import { ref, onMounted, reactive, toRefs, watch } from 'vue'
	import { init } from '@/public/package-js/init.js'
	import { Upload } from '@/public/package-js/uploadImg.js'
	import { FeedBack } from "@/public/package-js/feedBack.js"
	// 引入传值数据
	import { related_good } from "@/public/package-js/passValue.js"

	// 1、控制弹窗弹出
	const show = ref(false);

	// 弹窗遮罩层进入时触发，不写弹窗没法出来
	function onEnter(e) {}

	onMounted(() => {
		getBanner()
	})

	const data = reactive({
		bannerList: [], // 存储横幅数据
		banner_cover: '', //用于上传后展示图片
		fileId:'', // 上传横幅图片的 id
		relatedData: { // 用来存储关联商品的数据
			title: '', // 商品标题
			goods_id: '', // 商品的 id
			video_url: '' // 商品视频链接
		}
	})
	const { bannerList, banner_cover, relatedData } = toRefs(data)

	// 1、 获取数据库中的横幅数据
	async function getBanner() {
		let db = await init()
		let res = await db.database().collection('banner').get()
		data.bannerList = res.data
	}

	// 2、上传横幅图片
	async function uploadImg() {
		const local = await new Upload().image()
		uni.showLoading({
			title: '正在上传',
			mask: true
		})
		// 将图片上传到云存储
		const res = await new Upload().cloud(local[0].tempFilePath)
		data.banner_cover = res.tempFileURL //将真实路径赋值  
		data.fileId = res.fileID
		uni.hideLoading()
	}

	// 3、点击删除横幅上传的横幅
	function delImg() {
		uni.showModal({
			title: '提示',
			content: '确定删除该图片吗？',
			success: async function(res) {
				if (res.confirm) {
					uni.showLoading({
						title: '删除中',
						mask: true
					});
					// 删除云端的图片
					// 因为上传的图片 id push 进数组的最后
					await new Upload().delFile(data.fileId)
					
					// 删除渲染的图片
					data.banner_cover = ''
					new FeedBack("删除成功", "success").toast()

				} else if (res.cancel) {
					new FeedBack("取消操作", "error").toast()
				}
			}
		});
	}

	// 4、点击添加关联商品，跳转页面并携带已经关联的横幅id数组
	function addRelated() {
		// 将横幅列表中关联的商品的 id 取出来
		// console.log("data.bannerList",data.bannerList);
		const rel_id = data.bannerList.map(item => item.goods_id)
		// 将数组转为字符串，携带参数传递
		const str_id = JSON.stringify(rel_id)
		uni.navigateTo({
			url: '/pages/related_goods/related_goods?related_id=' + str_id
		})
	}

	// 5、监听关联的商品发生变化，并将数据存储起来
	watch(related_good, (newVal, oldVal) => {
		// console.log("newVal",newVal);
		// 将值存起来
		data.relatedData.title = newVal.goods_title
		data.relatedData.goods_id = newVal.goods_id
		data.relatedData.video_url = newVal.video_url
	})

	// 6、点击提交验证
	function submit() {
		switch (true) {
			case data.banner_cover == '':
				new FeedBack('请上传封面图', "error").toast()
				break;
			case data.relatedData.title == '':
				new FeedBack('请关联一个商品', "error").toast()
				break;
			default:
				commit()
				break;
		}
	}

	// 6-1 提交数据库
	async function commit() {
		uni.showLoading({
			title: '正在提交',
			mask: true
		})

		// 将关联的商品信息进行组装，以便提交到数据库
		let obj = {
			banner_cover: data.banner_cover,
			goods_id: data.relatedData.goods_id,
			video_url: data.relatedData.video_url
		}
		try {
			let db = await init()
			await db.database().collection('banner').add({
				data: obj
			})
			// 关闭弹窗，清空弹窗的数据
			show.value = false
			data.banner_cover = '';
			data.relatedData.title = ''
			// 调用方法请求数据库的横幅
			getBanner()
			new FeedBack('提交成功', 'success').toast()
		} catch (e) {
			new Feedback('提交失败',"error").toast()
		}
	}

	// 7、点击删除横幅
	async function delBanner(id,index){
		uni.showModal({
			title: '提示',
			content: '确定删除该横幅吗？',
			success: async function(res) {
				if (res.confirm) {
					try{
						uni.showLoading({
							title: '删除中',
							mask: true
						});
						let db = await init()
						// 云端删除横幅数据
						await db.database().collection('banner').doc(id).remove()
						// 渲染的横幅删除
						data.bannerList.splice(index,1)
					
						new FeedBack('删除成功','success').toast()
					}catch(e){
						new FeedBack('删除失败',"error").toast()
						console.log("错误",e);
					}
				} else if (res.cancel) {
					new FeedBack("取消操作", "error").toast()
				}
			}
		});
	
	}


</script>

<style scoped>
	.popup-padding {
		padding-bottom: 60rpx !important;
	}

	.upload-cover {
		position: relative;
	}

	.upload-cover image:nth-child(1) {
		width: 100%;
		height: 380rpx;
		display: block;
	}

	.upload-cover image:nth-child(2) {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		top: 6rpx;
		right: 6rpx;
	}

	.relation-back {
		background-color: #f7f7f7 !important;
		color: #000000 !important;
	}

	.over-text {
		color: #ed6b51 !important;
	}
</style>